import { useState } from 'react'

export function useLocalStorage(key: string, isObject = false) {
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = localStorage.getItem(key)
      if (!isObject) return item
      return item ? JSON.parse(item) : null
    } catch (error) {
      console.error(error)
      return null
    }
  })

  const setValue = (newValue: any) => {
    try {
      localStorage.setItem(key, isObject ? JSON.stringify(newValue) : newValue)
    } catch (err) {
      console.error(err)
    }
    setStoredValue(newValue)
  }

  return [storedValue, setValue]
}
